package com.youthburin.rmp.services.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.youthburin.base.services.AbstractService;
import com.youthburin.base.springjpa.MyRepository;
import com.youthburin.rmp.domain.RmpDept;
import com.youthburin.rmp.repositories.RmpDeptRepository;
import com.youthburin.rmp.services.RmpDeptService;

@Service
public class RmpDeptServiceImpl extends AbstractService<RmpDept, String> implements RmpDeptService {
	@Autowired
	private RmpDeptRepository rmpDeptRepository;

	@Override
	public MyRepository<RmpDept, String> getMyRepository() {
		return rmpDeptRepository;
	}

	@Override
	@Cacheable("rmp-dept-cache")
	public String getTreeString(String treeClass) {
		return getSubTree(null, treeClass).toString();
	}

	private StringBuffer getSubTree(String parentCode, String treeClass) {
		StringBuffer str = new StringBuffer();
		List<RmpDept> deptList = null;
		if (parentCode == null) {
			deptList = rmpDeptRepository.findByParentCodeIsNull();
		} else {
			deptList = rmpDeptRepository.findByParentCode(parentCode);
		}
		if (deptList == null || deptList.isEmpty()) {
			return null;
		}

		str.append("<ul");
		if (StringUtils.isNotBlank(treeClass)) {
			str.append(" class='").append(treeClass).append("' ");
		}
		str.append(">");

		for (RmpDept dept : deptList) {
			List<RmpDept> subDeptList = rmpDeptRepository.findByParentCode(dept.getCode());

			if (subDeptList == null || subDeptList.isEmpty()) {
				str.append("<li><a href='javascript:' onclick='$.bringBack({code:\"").append(dept.getCode())
						.append("\", name:\"").append(dept.getName()).append("\"})'>").append(dept.getName())
						.append("</a></li>");
			} else {
				str.append("<li><a href='javascript:' onclick='$.bringBack({code:\"").append(dept.getCode())
						.append("\", name:\"").append(dept.getName()).append("\"})'>").append(dept.getName())
						.append("</a>");
				str.append(getSubTree(dept.getCode(), null));
				str.append("</li>");
			}
		}

		str.append("</ul>");

		return str;
	}
}
